package com.example.hms.util;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@Configuration
public class TokenInter implements HandlerInterceptor {
    private long refreshTime = 1000 * 60 * 3;//TOKEN过期时间为3小时 1个用法




    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("拦截器拦截成功，默认放行");
        //第一步：创建Session
        HttpSession session = httpServletRequest.getSession();
        //第二步：从Session中获取用户名
        String userId = (String) session.getAttribute("userId");
        //第三步：校验用户名是否存在
        if (userId == null || userId.equals("")) {
            //第四步：如果用户名不存在,则证明Session不存在用户信息，那么返回报错
            //用户未登录，同时返回拦截器拦截
            returnJson(httpServletResponse, JSONCreate("用户未登录"));//生成报错信息
            return false;
        } else {
            //第五步：如果用户存在，则从Session获取TOKEN
            Map<String, Object> map = TokenUtil.checkToken(
                    (String) session.getAttribute("token"));
            //第六步：TOKEN解密,获取用户名信息,和Session中的用户信息比较,如果不同,
            // 则证明用户信息有误,返回报错,用户信息有误，同时返回拦截器拦截
            if (!map.get("userId").equals(userId)) {
                returnJson(httpServletResponse, JSONCreate("用户信息有误"));//生成报错信息
                return false;
            } else {
                //第七步：将TOKEN中的时间戳和当前系统时间比较，确认是否超过3个小时
                //如果超过了，则证明用户3小时未操作，返回报错信息，TOKEN过期，
                //请重新登录，同时返回拦截器拦截
                if (System.currentTimeMillis() - (Long) map.get("time") > refreshTime) {
                    returnJson(httpServletResponse, JSONCreate("TOKEN过期，" +
                            "请重新登录"));//生成报错信息
                    return false;
                } else {
                    //第八步：生成系统当前时间戳
                    return true;
                }
            }
        }
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("业务执行完毕");
        HttpSession session = request.getSession();
        String userId = (String) session.getAttribute("userId");
        String roleName = (String) session.getAttribute("roleName");
        session.setAttribute("token",TokenUtil.getToken(
                userId,roleName,System.currentTimeMillis()));
    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("视图渲染完毕");
    }

    // 创建错误信息时返回信息
    private String JSONCreate(String message){
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("{\"code\":-1,\"message\":\"");
        stringBuffer.append(message);
        stringBuffer.append("\"}");
        return stringBuffer.toString();
    }


    private void returnJson(HttpServletResponse response, String result) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(result);

        } catch (IOException e) {
        } finally{
            if (writer != null) {
                writer.close();
            }
        }
    }
}

